<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>车辆模拟运行监控系统</title>

  <link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet">
  <!-- Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>

  <!-- 配置Tailwind自定义颜色 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#00a3ff',
            secondary: '#00ffdd',
            accent: '#ff3d71',
            dark: '#050e2d',
            darker: '#03091e',
            'dark-card': '#0a193a',
            'dark-border': '#162955'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .glow {
        box-shadow: 0 0 10px rgba(0, 163, 255, 0.5);
      }
      .glow-accent {
        box-shadow: 0 0 10px rgba(255, 61, 113, 0.7);
      }
      .text-shadow {
        text-shadow: 0 0 8px rgba(0, 163, 255, 0.7);
      }
      .bg-grid {
        background-image: 
          linear-gradient(rgba(22, 41, 85, 0.1) 1px, transparent 1px),
          linear-gradient(90deg, rgba(22, 41, 85, 0.1) 1px, transparent 1px);
        background-size: 20px 20px;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
      .gradient-border {
        position: relative;
        border: double 1px transparent;
        background-image: linear-gradient(#0a193a, #0a193a), 
                          linear-gradient(to right, #00a3ff, #00ffdd);
        background-origin: border-box;
        background-clip: padding-box, border-box;
      }
    }
  </style>
</head>

<body class="bg-dark text-gray-200 min-h-screen bg-grid overflow-x-hidden">

  <!-- 顶部导航栏 -->
  <header class="flex items-center justify-between px-6 py-4 bg-darker border-b border-dark-border">
    <div class="flex items-center space-x-6">
      <h1 class="text-2xl font-bold text-primary text-shadow">车辆模拟运行监控系统</h1>
    </div>
    <div class="flex items-center space-x-4">
      <a href="vehicle-monitoring.html"
        class="bg-dark-card hover:bg-opacity-80 text-primary border border-dark-border px-4 py-2 rounded-md transition-all duration-300 flex items-center gap-2">
        <i class="fas fa-monitor"></i>
        <span>模拟详情</span>
      </a>
    </div>
  </header>

  <main id="dashboard-main" class="p-6">
    <!-- 1. KPI卡片区域 -->
    <section class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-primary hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">方案总数</h3>
        <p class="text-2xl font-bold text-primary" id="kpi-total-optimizations">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-primary hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">平均综合绩效得分</h3>
        <p class="text-2xl font-bold text-primary" id="kpi-avg-cost">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-secondary hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">最高资源利用</h3>
        <p class="text-2xl font-bold text-secondary" id="kpi-resourceUtilizationScore">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-secondary hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">最高满意度</h3>
        <p class="text-2xl font-bold text-secondary" id="kpi-satisfactionScore">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-accent hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">最少成本得分</h3>
        <p class="text-2xl font-bold text-accent" id="kpi-costScore">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-accent hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">最少耗时得分</h3>
        <p class="text-2xl font-bold text-accent" id="kpi-timeScore">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-accent hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">最少距离得分</h3>
        <p class="text-2xl font-bold text-accent" id="kpi-distanceScore">-</p>
      </div>
      <div
        class="bg-dark-card p-4 rounded-lg border border-dark-border border-l-4 border-accent hover:shadow-lg transition-all duration-300">
        <h3 class="text-sm text-gray-400 mb-2">最少碳排得分</h3>
        <p class="text-2xl font-bold text-accent" id="kpi-carbonEmissionsScore">-</p>
      </div>
    </section>

    <!-- 2. 图表区域 -->
    <section class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
      <!-- 3D柱状图 - 性能矩阵 -->
      <div class="bg-dark-card p-4 rounded-lg border border-dark-border">
        <h2 class="text-xl font-bold mb-4 text-primary">性能矩阵 [3D]</h2>
        <div id="chart-3d" class="h-[400px] w-full"></div>
      </div>
      <!-- 折线图 - 综合绩效得分曲线 -->
      <div class="bg-dark-card p-4 rounded-lg border border-dark-border">
        <h2 class="text-xl font-bold mb-4 text-primary">综合绩效得分曲线</h2>
        <div id="chart-line" class="h-[400px] w-full"></div>
      </div>
    </section>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts-gl@2.0.8/dist/echarts-gl.min.js"></script>

  <script>
    // DOM元素获取和ECharts实例初始化...
    const chart3DDom = document.getElementById('chart-3d');
    const chartLineDom = document.getElementById('chart-line');
    const dashboardMain = document.getElementById('dashboard-main');
    const chart3D = echarts.init(chart3DDom, 'dark');
    const chartLine = echarts.init(chartLineDom, 'dark');
    const apiUrl = 'http://localhost:8080/VRP/home';

    // ECharts主题颜色 - 与vehicle-monitoring.html保持一致
    const themeColors = {
      text: '#c9d1d9',
      glow: '#00a3ff',
      axisLine: 'rgba(0, 163, 255, 0.3)',
      splitLine: 'rgba(0, 163, 255, 0.1)',
      visualMap: ['#ff3d71', '#00a3ff', '#00ffdd', '#1DE9B6']
    };

    async function loadDashboard() {
      chart3D.showLoading(); chartLine.showLoading();
      try {
        const response = await fetch(apiUrl, { method: 'POST' });
        if (!response.ok) throw new Error(`API 请求失败: ${response.status}`);
        const apiData = await response.json();

        updateAllKpis(apiData);
        render3DChart(apiData);
        renderLineChart(apiData);
      } catch (error) {
        console.error('看板加载失败:', error);
        dashboardMain.innerHTML = `<div class="text-center p-10 text-xl text-accent"><h2>>> [连接中断]</h2><p>无法连接至后端服务: ${apiUrl}</p><p>错误: ${error.message}</p></div>`;
      }
    }

    // 2. 更新后的KPI数据处理函数
    function updateAllKpis(data) {
      if (!data || data.length === 0) return;

      // --- 宏观指标 ---
      const totalOptimizations = data.length;
      document.getElementById('kpi-total-optimizations').innerText = totalOptimizations;

      const totalCost = data.reduce((sum, item) => sum + item.synthesisScore, 0);
      document.getElementById('kpi-avg-cost').innerText = `${(totalCost / totalOptimizations).toFixed(0)}`;

      // --- 最优值指标 ---
      // Helper function to extract all values for a specific metric
      const getValues = (metric) => data.map(item => item.systemPerformanceMetrics[metric]);

      // Higher is better
      document.getElementById('kpi-resourceUtilizationScore').innerText = Math.max(...getValues('resourceUtilizationScore'));
      document.getElementById('kpi-satisfactionScore').innerText = Math.max(...getValues('satisfactionScore'));

      // Lower is better
      document.getElementById('kpi-costScore').innerText = Math.min(...getValues('costScore'));
      document.getElementById('kpi-timeScore').innerText = Math.min(...getValues('timeScore'));
      document.getElementById('kpi-distanceScore').innerText = Math.min(...getValues('distanceScore'));
      document.getElementById('kpi-carbonEmissionsScore').innerText = Math.min(...getValues('carbonEmissionsScore'));
    }

    // 图表渲染函数 (参数简化，因为内部可以直接处理数据)
    function render3DChart(apiData) {
      const metricMap = { "resourceUtilizationScore": "资源利用", "costScore": "成本", "timeScore": "耗时", "distanceScore": "距离", "carbonEmissionsScore": "碳排", "satisfactionScore": "满意度" };
      const xAxisCategories = apiData.map(item => item.optimizationName);
      const yAxisMetricKeys = Object.keys(metricMap);
      const yAxisCategories = Object.values(metricMap);
      const seriesData3D = [];
      apiData.forEach((opt, xIdx) => yAxisMetricKeys.forEach((key, yIdx) => seriesData3D.push([xIdx, yIdx, opt.systemPerformanceMetrics[key] || 0])));

      const option3D = {
        backgroundColor: 'transparent',
        tooltip: { backgroundColor: 'rgba(13, 17, 23, 0.9)', borderWidth: 1, borderColor: themeColors.axisLine, textStyle: { color: themeColors.text } },
        visualMap: { max: 100, inRange: { color: themeColors.visualMap }, textStyle: { color: themeColors.text } },
        grid3D: { boxWidth: 200, boxDepth: 120, viewControl: { autoRotate: true }, light: { main: { intensity: 1.2 }, ambient: { intensity: 0.3 } }, axisLine: { lineStyle: { color: themeColors.axisLine } }, axisLabel: { color: themeColors.text }, splitLine: { lineStyle: { color: themeColors.splitLine } } },
        xAxis3D: { type: 'category', data: xAxisCategories, nameTextStyle: { color: themeColors.text } },
        yAxis3D: { type: 'category', data: yAxisCategories, nameTextStyle: { color: themeColors.text } },
        zAxis3D: { type: 'value', name: '分数', max: 100, nameTextStyle: { color: themeColors.text } },
        series: [{ type: 'bar3D', data: seriesData3D, shading: 'lambert' }]
      };
      chart3D.hideLoading();
      chart3D.setOption(option3D);
    }

    function renderLineChart(apiData) {
      const xAxisCategories = apiData.map(item => item.optimizationName);
      const seriesDataLine = apiData.map(item => item.synthesisScore);

      const optionLine = {
        backgroundColor: 'transparent',
        tooltip: { trigger: 'axis', backgroundColor: 'rgba(13, 17, 23, 0.9)', borderWidth: 1, borderColor: themeColors.axisLine },
        grid: { left: '15%', right: '8%', bottom: '20%' },
        xAxis: { type: 'category', data: xAxisCategories, axisLine: { lineStyle: { color: themeColors.axisLine } }, axisLabel: { interval: 0, rotate: -45, color: themeColors.text } },
        yAxis: { type: 'value', name: '综合分数 (Synthesis Score)', splitLine: { lineStyle: { color: themeColors.splitLine } }, nameTextStyle: { color: themeColors.text }, axisLabel: { color: themeColors.text, formatter: '{value}' } },
        series: [{
          data: seriesDataLine, type: 'line', smooth: true, symbol: 'circle', symbolSize: 8,
          lineStyle: { color: themeColors.glow, width: 3, shadowColor: themeColors.glow, shadowBlur: 10 },
          itemStyle: { color: themeColors.glow },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0, color: 'rgba(0, 229, 255, 0.5)'
            }, {
              offset: 1, color: 'rgba(0, 229, 255, 0.05)'
            }])
          }
        }]
      };
      chartLine.hideLoading();
      chartLine.setOption(optionLine);
    }

    window.addEventListener('resize', () => { chart3D.resize(); chartLine.resize(); });
    loadDashboard();
  </script>
</body>

</html>